--boxani 1,3对反了。。
require "Cocos2d"
require "AudioEngine"
local visibleSize = cc.Director:getInstance():getVisibleSize()
local visibleOrigin = cc.Director:getInstance():getVisibleOrigin()
local GameState = {nomal=1, think=2, showFinal=3, sleep=4}

local game_1_2_1_2_Scene = class("game_1_2_1_2_Scene",function ()
    return cc.Layer:create()
end)
game_1_2_1_2_Scene._perScene=nil
game_1_2_1_2_Scene.__index=game_1_2_1_2_Scene
function game_1_2_1_2_Scene:createScene()
    require "gameScene"
    local layer = game_1_2_1_2_Scene:create()
    layer._perScene = gameSceneInstance
    return layer
end

function game_1_2_1_2_Scene:create()
    local layer = game_1_2_1_2_Scene:new()
    return layer
end

function game_1_2_1_2_Scene:ctor()
    print("ctor")
    local function sceneEventHandler(eventType)
        if eventType == "enter" then
            self:onEnter()
        elseif eventType == "exit" then
            self:onExit()
        end
    end
    self:registerScriptHandler(sceneEventHandler)
    self._role = nil
    self._Panel_root = nil
    self._quesTable = {{1,1},{1,2},{1,3},{1,4},{2,1},{2,2},{2,3},{3,1},{3,2},{4,1}}
    self._maxNum = 5 --题目数量
    self._nowQues = nil -- 当前的题目
    self.isTouchableOrNot = nil
    self.score = 0
    self.littleGameTimes = nil    -- 小游戏运行了几个
    self._sleepId = nil
    self._actionName = nil
    self.buttonBear = nil
    self.shadowTable = {} -- 影子table
    self._panel_tree1 = nil -- 两棵树
    self._panel_tree2 = nil
    self._isBingo=true
    self._aniDate={
        stand={ani={"think","standby_1","standby_2"},loop=false,music=nil,musicId=nil},
        chuo={ani="chuo",loop=false,music="click.mp3",musicId=nil},
        bingo={ani="end_start",loop=false,music=nil,musicId=nil},
        bingo2={ani="end_ing",loop=false,music=nil,musicId=nil},
        bingo3={ani="end_end",loop=false,music=nil,musicId=nil},
        right={ani="right",loop=false,music="right2.mp3",musicId=nil},
        wrong={ani="wrong",loop=false,music="wrong2.mp3",musicId=nil},
        think={ani="think",loop=false,music="think.mp3",musicId=nil},--??
        sleepstart={ani="sleep_1",loop=false,music=nil,musicId=nil},
        sleeping={ani="sleep_2",loop=true,music="sleeping2.mp3",musicId=nil},
        wakeiup={ani="sleep_3",loop=false,music=nil,musicId=nil}
    }
end

function game_1_2_1_2_Scene:onEnter()
    print("on scene enter")
    self.isTouchableOrNot = false
    -- 初始化画面
    self._uiLayer = cc.Layer:create()
    self:addChild(self._uiLayer)
    self:runAction(cc.Sequence:create(cc.DelayTime:create(0.1),cc.CallFunc:create(function()
        --        cc.Director:getInstance():getTextureCache():addImage("class2-02-B1.png")
        --        ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("class2-02-E/class2-02-E.ExportJson")
        ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("ani/kuma_little/kuma_little.ExportJson")
        for i=0, 5 do
            cc.Director:getInstance():getTextureCache():addImage("game_1_2_1_2/game_1_2_1_2_"..i..".png")
        end
        cc.Director:getInstance():getTextureCache():addImage("game_1_2_1_2/game_1_2_1_2_apple.png")
        cc.Director:getInstance():getTextureCache():addImage("game_1_2_1_2/game_1_2_1_2_shadow.png")
        self:init()
    end)))


end

function game_1_2_1_2_Scene:onExit()
    cclog("game_1_2_1_2_Scene--->onExit")
    ccs.ArmatureDataManager:getInstance():removeArmatureFileInfo("ani/kuma_little/kuma_little.ExportJson")
    for i=0, 5 do
        cc.Director:getInstance():getTextureCache():removeTextureForKey("game_1_2_1_2/game_1_2_1_2_"..i..".png")
    end
    cc.Director:getInstance():getTextureCache():removeTextureForKey("game_1_2_1_2/game_1_2_1_2_apple.png")
    cc.Director:getInstance():getTextureCache():removeTextureForKey("game_1_2_1_2/game_1_2_1_2_shadow.png")
    ccs.SceneReader:destroyInstance()
    ccs.ActionManagerEx:destroyInstance()
    ccs.GUIReader:destroyInstance()
    ccs.ArmatureDataManager:destroyInstance()

end

function game_1_2_1_2_Scene:init()
    cclog("==========>init")
    local m_scene_root = ccs.SceneReader:getInstance():createNodeWithSceneFile("game_1_2_1_2_Scene.json")
    self:addChild(m_scene_root)

    self._Panel_root = m_scene_root:getChildByTag(10003):getChildByTag(2)
    for iv=1, 2 do
        self["_panel_tree"..iv] = self._Panel_root:getChildByName("Panel_tree_"..iv)
    end

    self.littleGameTimes = 1
    self:SceneInit()
    self:runAction(cc.Sequence:create(cc.DelayTime:create(2),cc.CallFunc:create(function()
        self.isTouchableOrNot = true
    end)))
end

--播放动画
function game_1_2_1_2_Scene:playAction(_type)
    if _type==self._aniDate.stand then
        local function callBack()
            cclog("sleep===>")
            self._state=GameState.sleep
            self:playAction(self._aniDate.sleepstart)
        end
        if self._sleepId==nil then
            self._sleepId=self:runAction(cc.Sequence:create(cc.DelayTime:create(15),cc.CallFunc:create(callBack)))
        end
    else
        if self._sleepId~=nil then
            self:stopAction(self._sleepId)
            self._sleepId=nil
        end
    end

    local aniNames=_type.ani
    local loop=_type.loop
    local musicName=_type.music
    if musicName~=nil then
        cclog("musicName-->"..musicName)
    end
    if type(aniNames)=="table" then
        math.randomseed(tostring(os.time()):reverse():sub(1, 6))
        aniNames=aniNames[math.random(2,3)]
        --        if aniNames=="standby_1" then musicName= "look2.mp3" end
        --if aniNames=="standby_2" then musicName="look.mp3" end
        --print("rrrr:"..aniNames)
    end
    if self._actionName==_type and _type~=self._aniDate.stand then print("return") return end
    for k,v in pairs(self._aniDate) do
        if v.musicId~=nil then
            AudioEngine.stopEffect(v.musicId)
            v.musicId=nil
        end
    end
    self._actionName=_type
    --    cclog("aniNames----->"..aniNames)
    self._role:getAnimation():play(aniNames)
    if musicName~=nil then
        _type.musicId=AudioEngine.playEffect(musicName,_type.loop)
    end
end

-- 初始化画面
function game_1_2_1_2_Scene:SceneInit()
    this = self
    self:runAction(cc.Sequence:create(cc.DelayTime:create(1.0),cc.CallFunc:create(function() 
        AudioEngine.playMusic("game2.mp3",true)
    end)))
    -- 动画
    ccs.ArmatureDataManager:getInstance():removeArmatureFileInfo("ani/kuma_little/kuma_little.ExportJson")
    ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("ani/kuma_little/kuma_little.ExportJson")
    self._role=ccs.Armature:create("kuma_little")
    self._Panel_root:addChild(self._role,2)
    self._role:setPosition(cc.p(300,190))
    self._role:setScale(0.5)
    local function animationEvent(armatureBack,movementType,movementID)
        local id = movementID
        if movementType == ccs.MovementEventType.loopComplete or movementType==ccs.MovementEventType.complete then
            if id == "standby"  or id=="standby_1" or id=="standby_2" then
                --            print("jinru")
                self:playAction(self._aniDate.stand)
            end
            if id=="chuo" then
                self:playAction(self._aniDate.stand)
                self._state=GameState.nomal
            end
            if id=="think" then
                self:playAction(self._aniDate.stand)
            end
            if id=="wrong" then
                -- cclog("adadas")
                -- self:FinalcallBack()
                self:playAction(self._aniDate.stand)
                self._state=GameState.nomal

            end
            if id=="right" or id=="end_end"then
                cclog("----------creteNumber>")

                self:playAction(self._aniDate.stand)
                --                self._state=GameState.nomal
            end
            if id=="end_start" then
                AudioEngine.playEffect("yeah1.mp3",false)
                self:playAction(self._aniDate.bingo2)
            end
            if id=="end_ing" then
                self:playAction(self._aniDate.bingo3)
            end
            if id=="sleep_1" then
                self:playAction(self._aniDate.sleeping)
            end
            if id=="sleep_3" then
                --                AudioEngine.stopEffect(self.musicId)
                if self._nextAction~=nil then
                    --                cclog("adada")
                    self:playAction(self._nextAction)
                    self._nextAction=nil
                else
                    --                    cclog("adadadadad")
                    self:playAction(self._aniDate.stand)
                end
            end
        end
    end
    self._role:getAnimation():setMovementEventCallFunc(animationEvent)
    self:playAction(self._aniDate.stand)
    self.buttonBear = self._Panel_root:getChildByName("Button_Bear")
    self.buttonBear:setOpacity(0)
    self.buttonBear:addTouchEventListener( function ( pSender, eventType )
        if self._isTouchableOrNot ==false then return end
        if eventType ~= ccui.TouchEventType.ended then return  end
        if eventType == ccui.TouchEventType.ended then
            if self.isTouchableOrNot == false then return end
            cclog("----buttonBear_touchdown")
            if self._actionName==self._aniDate.stand then --站立被点击
                self:playAction(self._aniDate.chuo)
            end
            if self._state==GameState.sleep then --睡觉被点击
                self:playAction(self._aniDate.wakeiup)
                --AudioEngine.stopEffect(self.musicId)
                self._state=GameState.nomal
            end
        end
    end)
    self:runAction(cc.Sequence:create(cc.DelayTime:create(1.0),cc.CallFunc:create(function() 
        self:InitGame()
    end)))

end

function game_1_2_1_2_Scene:BusComeIn()
    for key, var in pairs(self._Panel_root:getChildByName("Panel_bus"):getChildren()) do
        if var:getTag()>99 then
            var:removeFromParent()
        end
    end
    self._Panel_root:getChildByName("Panel_bus"):getChildByName("Image_num"):loadTexture("game_1_2_1_2_0.png")
    AudioEngine.playEffect("bus_arrives.mp3")
    ccs.ActionManagerEx:getInstance():playActionByName("game_1_2_1_2_Ui_1.json","busIn",cc.CallFunc:create(function()
        self.IsSwitchOrNot = false
        self.isTouchableOrNot = true
    end))
end

function game_1_2_1_2_Scene:InitQues()
    local t_index = math.random(1,#self._quesTable)
    self._nowQues = self._quesTable[t_index]
    table.remove(self._quesTable,t_index)
end

function game_1_2_1_2_Scene:InitTrees()
    -- 树上和车上苹果的位置
    local tree1_pos = {cc.p(431,621),cc.p(426,431),cc.p(578,587),cc.p(596,506),cc.p(494,518),cc.p(386,503)}
    local tree2_pos = {cc.p(966,580),cc.p(773,488),cc.p(1000,495),cc.p(884,525),cc.p(793,576),cc.p(951,420)}
    local bus_pos = {cc.p(680,322),cc.p(752,322),cc.p(619,314),cc.p(645,364),cc.p(719,363)}
    -----------触摸事件
    -- 触摸开始
    local function touch(pSender, touchEventType)
        local function endlogic(nowNum)
            local Image_num = self._Panel_root:getChildByName("Panel_bus"):getChildByName("Image_num")
            Image_num:loadTexture("game_1_2_1_2_"..nowNum..".png")

            if nowNum == self._nowQues[1]+self._nowQues[2] then
                self:playAction(self._aniDate.bingo)
                -- moveper
                self.score = self.score+20
                cc.Director:getInstance():getRunningScene():movePer(self.score,cc.p(0,0))
                local function readFunc()
                    AudioEngine.playEffect("zuhe"..self._nowQues[1].."-"..self._nowQues[2]..".mp3")
                end
                self:runAction(cc.Sequence:create(cc.DelayTime:create(1),cc.CallFunc:create(readFunc),cc.DelayTime:create(2),cc.CallFunc:create(function( )
                    ccs.ActionManagerEx:getInstance():playActionByName("game_1_2_1_2_Ui_1.json","busOut",cc.CallFunc:create(function()
                        self._panel_tree1:getChildByName("Image_num"):setOpacity(0)
                        self._panel_tree2:getChildByName("Image_num"):setOpacity(0)
                        if self.littleGameTimes >=self._maxNum+1 then return end
                        self:InitGame()   
                    end))
                end)))
                self.littleGameTimes = self.littleGameTimes+1
                cclog("littleGameTimes------>"..self.littleGameTimes)
                if self.littleGameTimes == self._maxNum+1 then
                    self:runAction(cc.Sequence:create(cc.DelayTime:create(4.0),cc.CallFunc:create(function()
                        self.isTouchableOrNot =false
                        self._role:getAnimation():gotoAndPause(1)
                        if self._sleepId~= nil then
                            self:stopAction(self._sleepId)
                            self._sleepId=nil
                        end
                        self._perScene:endLayer(1,2,1,2,self.score)
                        return
                    end)))
                    return
                    
                end
            end
        end
        if touchEventType == ccui.TouchEventType.began  then
            print("---------------------------TOUCH_EVENT_BEGAN")
            if self._sleepId~=nil then
                self:stopAction(self._sleepId)
                self._sleepId=nil
            end
            local function nosleepFunc()
                if self._state==GameState.sleep then
                    self._nextAction=self._aniDate.stand
                    self:playAction(self._aniDate.wakeiup)
                    self._state = GameState.nomal
                end
            end
            self:runAction(cc.Sequence:create(cc.DelayTime:create(0.0),cc.CallFunc:create(nosleepFunc)))
            if self.isTouchableOrNot == false then cclog("touchableOrnot..") return end
            if self.IsSwitchOrNot == true then cclog("正在切换。") return end
            self.IsSwitchOrNot = true
            pSender:setAnchorPoint(cc.p(0.5,0.5))
            local x,y = pSender:getPosition()
            pSender:setPosition(cc.p(x,y-33))
            pSender:stopAllActions()
            pSender:setRotation(0)
            pSender:retain()
            pSender:removeFromParent()
            local wolrdspace = pSender:convertToWorldSpaceAR(cc.p(0,0))
            local panel_bus = self._Panel_root:getChildByName("Panel_bus")
            local nodespace = panel_bus:convertToNodeSpace(wolrdspace)
            pSender:setPosition(nodespace)
            -- 检测panel_bus有多少子node
            local appleNum = #panel_bus:getChildren() - 3 -- 3为本来仅有的两个imageview
            if appleNum == 0 then
                AudioEngine.playEffect("one.mp3")
            elseif appleNum == 1 then
                AudioEngine.playEffect("two.mp3")
            elseif appleNum == 2 then
                AudioEngine.playEffect("three.mp3")
            elseif appleNum == 3 then
                AudioEngine.playEffect("four.mp3")
            else
                AudioEngine.playEffect("five.mp3")
            end

            local imge_shadow = ccui.ImageView:create("game_1_2_1_2_shadow.png")
            imge_shadow:setPosition(wolrdspace)
            table.insert(self.shadowTable,#self.shadowTable+1,imge_shadow)
            self._Panel_root:addChild(imge_shadow)
            pSender:runAction(cc.Sequence:create(cc.MoveTo:create(0.5,bus_pos[appleNum+1]),cc.CallFunc:create(function()
                AudioEngine.playEffect("jinru.mp3")
                self.IsSwitchOrNot = false
                endlogic(appleNum+1)
            end)))
            panel_bus:addChild(pSender,300,100+appleNum)
        elseif touchEventType == ccui.TouchEventType.moved then
            print("---------------------------TOUCH_EVENT_MOVED")
        else
            print("---------------------------TOUCH_EVENT_ENDED")
        end
    end

    local function InitApples(pal,index,posTab)
        self:playAction(self._aniDate.think)
        local sum = self._nowQues[index]
        local numImg=pal:getChildByName("Image_num")
        numImg:loadTexture("game_1_2_1_2_"..sum..".png")
        numImg:setOpacity(255)
        for ik=1, sum do
            local img_apple = ccui.ImageView:create("game_1_2_1_2_apple.png")
            img_apple:setAnchorPoint(cc.p(0.51,0.98))
            img_apple:runAction(cc.RepeatForever:create(cc.Sequence:create( cc.RotateBy:create(0.2,7),cc.RotateBy:create(0.4,-14),cc.RotateBy:create(0.2,7))))
            local index = math.random(1,#posTab)
            local Pos = posTab[index]
            img_apple:setPosition(Pos.x,Pos.y+33)
            img_apple:addTouchEventListener(touch)
            img_apple:setTouchEnabled(true)
            table.remove(posTab,index)
            pal:addChild(img_apple,30)
        end

    end

    InitApples(self._panel_tree1,1,tree1_pos)
    InitApples(self._panel_tree2,2,tree2_pos)
end

function game_1_2_1_2_Scene:InitGame()
    self.isTouchableOrNot = false
    self.IsSwitchOrNot = true
    if #self.shadowTable>0 then
        for key, var in pairs(self.shadowTable) do
            var:removeFromParent()
        end
        self.shadowTable = {}
    end
    self:InitQues()
    self:InitTrees()
    self:BusComeIn()
end

function crt_game_1_2_1_2_Scene()
    local _scene = game_1_2_1_2_Scene:createScene()
    return _scene
end